package com.ruoyi.business.service.impl;

import com.ruoyi.business.domain.BusCollectionItem;
import com.ruoyi.business.domain.CollectedData;
import com.ruoyi.business.domain.StationParameter;
import com.ruoyi.business.service.IAsherSocketService;
import com.ruoyi.business.service.ICollectedDataService;
import com.ruoyi.common.utils.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AsherSocketService implements IAsherSocketService {

    public static Socket s;

    public static Map<Integer, StationParameter> parameterMap = new HashMap(){
        {
//            put(1, new StationParameter(-3.87758, -2.55351, 1399.40, -4, 0));
//            put(2, new StationParameter(6.41755, 7.71846, 1495.10, -4, -1));
//            put(3, new StationParameter(2.30268, -5.79746, 1487.70, -4, -1));
//            put(4, new StationParameter(1.25934, 3.06105, 1586.00, -3, 0));
//            put(8, new StationParameter(7.52122, 1.10405, 1584.50, -4, 0));
//            put(7, new StationParameter(5.07636, -1.26180, 1522.10, -5, 0));
//            put(6, new StationParameter(5.96249, 4.50440, 1563.60, -4, -1));
//            put(5, new StationParameter(9.62836, 1.93590, 1482.40, -4, 0));
            put(1, new StationParameter(-3.87758, -2.55351, 1422.22, -4, 0));
            put(2, new StationParameter(6.41755, 7.71846, 1519.15, -4, -1));
            put(3, new StationParameter(2.30268, -5.79746, 1506.17, -4, -1));
            put(4, new StationParameter(1.25934, 3.06105, 1613.16, -3, 0));
            put(8, new StationParameter(7.52122, 1.10405, 1606.88, -4, 0));
            put(7, new StationParameter(5.07636, -1.26180, 1546.76, -5, 0));
            put(6, new StationParameter(5.96249, 4.50440, 1580.12, -4, -1));
            put(5, new StationParameter(9.62836, 1.93590, 1506.17, -4, 0));

        }
    };

    public static boolean socketCollect = false;

    public static Thread t;

    public static Long total = 80000000L;

    @Autowired
    private ICollectedDataService collectedDataService;

    @Override
    public void startCollectStationData(List<BusCollectionItem> busCollectionItems) {
        t = new Thread(new Runnable(){
            public void run(){
                try {
                    if (s == null) {
                        s = new Socket("192.168.1.107",26);
                    }
                    //构建IO
                    InputStream is = s.getInputStream();
                    OutputStream os = s.getOutputStream();

                    while(socketCollect) {
                        for (BusCollectionItem item : busCollectionItems) {
                            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(os));
//                    String ss = "FF55FFAA0201010051CC";
                            String ss = item.getChannelCode();
                            os.write(hexStringToByteArray(ss));
                            bw.flush();
                            byte[] bytes = new byte[24];
                            is.read(bytes);
                            String s1 = bytesToHexString(bytes);
                            String[] split = s1.split("");
                            ArrayList<String> res = new ArrayList<>();
                            for (int i = 12,j = 1; i <= 40; i = i + 4, j++) {
                                StationParameter stationParameter = parameterMap.get(j);
                                String front = split[i] + split[i+1];
                                String back = split[i+2] + split[i+3];
                                String full = back + front;
                                Long l = Long.parseLong(full,16);
                                System.out.println(l);
                                double hz = total.doubleValue() / l.doubleValue();
                                System.out.println("第" + j);
                                System.out.println(hz);
                                double hzPow = Math.pow(hz, 2);
                                double f0Pow = Math.pow(stationParameter.getF0(), 2);
                                double v = stationParameter.getA() * (hzPow - f0Pow);
                                double v1 = stationParameter.getB() * (hz - stationParameter.getF0());
                                double pasc = v - v1;
                                res.add(String.valueOf(pasc));
                            }
                            CollectedData collectedData = new CollectedData();
                            collectedData.setCollectItemId(item.getCollectionItemId());
                            collectedData.setChannelNo(item.getChannelId());
                            collectedData.setCreateTime(DateUtils.getNowDate().getTime());
                            collectedData.setFormula(String.join(",", res));
                            collectedData.setCardId("STATION");
                            collectedDataService.insertCollectedData(collectedData);
                            Thread.currentThread().sleep(500);
                            System.out.println("插入" + s1);
                        }
                    }
                } catch (UnknownHostException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            }});
        t.start();
    }

    public String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }


    public byte[] hexStringToByteArray(String str) {
        byte[] byteArray = new byte[str.length()/2];
        int len = byteArray.length;
        int j = 0;
        for (int i = 0; i<len; i++) {
            j = (i<<1);
            byteArray[i] = 0;
            char c = str.charAt(j);
            if ('0'<=c && c<='9') {
                byteArray[i] |= ((c-'0')<<4);
            } else if ('A'<=c && c<='F') {
                byteArray[i] |= ((c-'A'+10)<<4);
            } else if ('a'<=c && c<='f') {
                byteArray[i] |= ((c-'a'+10)<<4);
            } else {
            }
            j++;
            c = str.charAt(j);
            if ('0'<=c && c<='9') {
                byteArray[i] |= (c-'0');
            } else if ('A'<=c && c<='F') {
                byteArray[i] |= (c-'A'+10);
            } else if ('a'<=c && c<='f') {
                byteArray[i] |= (c-'a'+10);
            } else {

            }
        }
        return byteArray;
    }

    public byte[] getStreamBytes(InputStream is) throws Exception {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = is.read(buffer)) != -1) {
            baos.write(buffer, 0, len);
        }
        byte[] b = baos.toByteArray();
        is.close();
        baos.close();
        return b;
    }
}
